package com.dbapp.garden.config.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启方法级安全的权限控制
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

	 @Autowired
	private BCryptPasswordEncoder bCryptPasswordEncoder;
	//
	// @Autowired
	// private DataSource dataSource;


	@Autowired
	private CustomUserDetailServiceImpl userDetailService;


	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(userDetailService).passwordEncoder(bCryptPasswordEncoder);
		// .jdbcAuthentication()
		// .usersByUsernameQuery(usersQuery)
		// .authoritiesByUsernameQuery(rolesQuery)
		// .dataSource(dataSource)
		// .passwordEncoder(bCryptPasswordEncoder);

	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
//		http.addFilterAfter(customSecurityFilter, UsernamePasswordAuthenticationFilter.class)
		http
		.headers().frameOptions().disable().and()
				.authorizeRequests().antMatchers("/").permitAll()
				.antMatchers("/login").permitAll()
				.antMatchers("/loginCheck").permitAll()
				.antMatchers("/registration").permitAll()
				//.antMatchers("/roles").hasAuthority("PERMISSION_ROLE")
				.anyRequest()
				.authenticated().and().csrf().disable().formLogin().loginPage("/login")
				.and().logout()
				.logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/").and()
				.exceptionHandling().accessDeniedPage("/access-denied");

		// http
		// .authorizeRequests()
		// .anyRequest().authenticated()
		// .and()
		// .formLogin()
		// .and()
		// .httpBasic();

	}

	@Override
	public void configure(WebSecurity web) throws Exception {
		web.ignoring().antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**","/media/**");
	}

}